package com.yunjing.udpsendreceivedata;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author dell-2
 * @file_name ThreadPoolManager
 * @describe 线程池管理类
 * @date 2023/3/18
 */
public class ThreadManager {

    private static ThreadManager threadPoolManager;
    private ScheduledThreadPoolExecutor scheduled;
    /**
     * 按需创建
     */
    private ExecutorService cachedThreadExecutor;

    /**
     * 获取线程池管理类实例
     * @return
     */
    public static ThreadManager getInstance(){
        if (threadPoolManager == null){
            synchronized (ThreadManager.class){
                if (threadPoolManager == null){
                    threadPoolManager = new ThreadManager();
                }
            }
        }
        return threadPoolManager;
    }

    /**
     * 获取延迟线程池或周期性线程池
     * @return
     */
    public ScheduledThreadPoolExecutor getScheduledThread(){

        if (scheduled == null){
            scheduled = new ScheduledThreadPoolExecutor(5);
        }

        return scheduled;
    }

    /**
     * 按需创建线程池
     * 没有核心线程，只有非核心线程：int最大值
     *
     * @return
     */
    public ExecutorService getCachedThreadPool() {

        if (cachedThreadExecutor == null) {
            //corePoolSize:核心线程池  maximumPoolSize:该线程池中最大线程数  keepAliveTime:线程保活时长  TimeUnit:保活时长单位 秒
            cachedThreadExecutor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new SynchronousQueue<>());
        }
        return cachedThreadExecutor;

    }

}
